(function($, undefined) {
  $.cha.js("lib.json2");
  
  $.cha.html("s3.login.login");
  $.cha.css("s3.login.login");

  $.widget("ui.s3loginview", {
    options : {
      key : null,
      secret : null,
      login : function(result) {
        console.log(result);
      }
    },
    _create : function() {
      var self = this;
      this.restore();
      var html = $.render(this.user, "cha.s3.login.login");
      $(html).appendTo(this.element);
      $(this.element).link(this.user);

      $(this.element).find(".save").bind("click.save", function() {
        self.save();
      });

      $(this.element).find(".login").bind(
          "click.login",
          function() {
            self.s3client = new $.cha.s3.S3Client(self.user.key,
                self.user.secret);
            self.s3client.bucketsList({
              success : function(data) {
                var result = $.cha.s3.XmlParser
                    .parseListAllMyBucketsResult(data);
                self.options.login(result);
              }
            });
          });
    },
    getS3client:function(){
      return this.s3client;
    },
    save : function() {
      var json = JSON.stringify(this.user);
      localStorage["s3user"] = json;
    },
    restore : function() {
      var json = localStorage["s3user"];
      if (json) {
        this.user = JSON.parse(json);
      } else {
        this.user = {
          key : this.options.key,
          secret : this.options.secret
        };
      }
    }
  });
}(jQuery));